using System.Collections;
using UnityEngine;
using UnityEngine.Networking;

namespace Miya.Hellow
{
    public class TextFileRequester : MonoBehaviour
    {

        public string Url;
        // Start is called before the first frame update

        public bool _Ready = false;

        public string Result;

        public string Error;

        public TextFileRequester SetUrl(string url)
        {
            Url = url; return this;
        }
        IEnumerator Start()
        {
            _Ready = false;

            yield return _FileReader(Url);

            _Ready = true;


            yield return new WaitForSeconds(0.2f);

            Destroy(gameObject);
        }
        IEnumerator _FileReader(string url)
        {
            Error = "";
            UnityWebRequest QQ = UnityWebRequest.Get(url);

            yield return QQ.SendWebRequest();
            while (!QQ.isDone)
                yield return 0;

            if (string.IsNullOrEmpty(QQ.error) && !string.IsNullOrEmpty(QQ.downloadHandler.text))
            {
                Error = "";
                Result = QQ.downloadHandler.text;
                Debug.Log($"[TextFileRequest._FileReader]:Url={url}  \n{Result} ");

            }
            else
            {
                Error = QQ.error;
                Debug.Log($"[TextFileRequest._FileReader]:Error={QQ.error} @{url}");

                if (!url.StartsWith("file://"))
                {
                    yield return _FileReader($"file://{url}");
                }
            }
        }
        public WaitUntil WaitEnd()
        {
            return new WaitUntil(() => { return _Ready; });
        }

        public static TextFileRequester Request(string url)
        {
            return new GameObject($"FileRequest(url)").AddComponent<TextFileRequester>().SetUrl(url);
        }
    }
}

